package com.zhu.responder.websocker.netty;

import com.zhu.responder.websocker.handler.MyNettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class NettyServer {
 
    private NioEventLoopGroup bossGroup = new NioEventLoopGroup(3);
    private NioEventLoopGroup workGroup = new NioEventLoopGroup();
    private Channel channel;
    private MyNettyServerHandler nettyServerHandler;
 
    public NettyServer (MyNettyServerHandler nettyServerHandler){
        this.nettyServerHandler=nettyServerHandler;
    }
 
    public ChannelFuture start(int port){
        try{
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workGroup)
                    //使用哪种通道实现,NioServerSocketChannel为异步的服务器端 TCP Socket 连接。
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    //设置连接队列长度
                    .option(ChannelOption.SO_BACKLOG,1024)
                    //添加拦截处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //websocket协议本身是基于http协议的，所以使用http解编码器
                            pipeline.addLast(new HttpServerCodec());
                            //post请求方式
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            //websocket协议
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
                            pipeline.addLast(nettyServerHandler);
                        }
                    });
            ChannelFuture channelFuture = bootstrap.bind().sync();
            channel=channelFuture.channel();
            log.info("netty 服务开启成功！");
            return channelFuture;
        }catch (Exception e){
            log.info("netty启动错误！{}",e);
        }
        return null;
    }
   public void destory(){
        if (channel!=null){
            channel.close();
        }
       bossGroup.shutdownGracefully();
       workGroup.shutdownGracefully();
       log.info("netty 服务关闭！");
   }
}